package top.codedance.iotp.tools.terminal.comer;

import top.codedance.iotp.tools.terminal.TerminalApplication;
import top.codedance.iotp.tools.terminal.bean.ComConnectParam;
import top.codedance.iotp.tools.terminal.comer.listenner.SerialPortListener;
import com.fazecast.jSerialComm.SerialPort;

import java.nio.charset.StandardCharsets;

public class ComClient {

    private CallOwner owner;
    private SerialPort mSerialPort = null;
    private ComConnectParam comConnectParam;
    private int sendCount = 0;

    public ComClient(CallOwner owner, ComConnectParam comConnectParam){
        this.owner = owner;
        this.comConnectParam = comConnectParam;
        connect();
    }

    private void connect(){
        if(mSerialPort == null) {
            mSerialPort = SerialPort.getCommPort(comConnectParam.getCom());
            mSerialPort.setFlowControl(SerialPort.FLOW_CONTROL_DISABLED);
            mSerialPort.setComPortParameters(comConnectParam.getBtl(), comConnectParam.getSjw(), comConnectParam.getTzw(), comConnectParam.getXyw());
            mSerialPort.addDataListener(new SerialPortListener(this));
        }
        if (!mSerialPort.openPort(0, 1024*1024*2, 1024*1024*2)) {
            mSerialPort = null;
            TerminalApplication.syslogInfo("The com port is occupied!");
        }else{
            TerminalApplication.syslogInfo("Com client is running!");
        }
    }

    public boolean isOpen(){
        return mSerialPort.isOpen();
    }

    public void close(){
        if(mSerialPort != null && mSerialPort.isOpen()) {
            mSerialPort.closePort();
        }
    }

    /**
     * 发送数据
     * @param data
     */
    public void send(String data){
        send(data.getBytes(StandardCharsets.UTF_8));
    }

    /**
     * 发送数据
     * @param bytes
     */
    public void send(byte[] bytes){
        if(mSerialPort == null || !mSerialPort.isOpen()) {
            connect();
        }else{
            if(sendCount > 3){
                close();
                connect();
            }
        }
        if(mSerialPort != null && mSerialPort.isOpen()) {
            mSerialPort.writeBytes(bytes, bytes.length);
            sendCount++;
        }
    }

    /**
     * 添加数据到界面
     * @param data
     */
    public void appendResult(String data){
        owner.appendResult(data);
        sendCount = 0;
    }

    /**
     * 添加错误数据到调用者
     * @param data
     */
    public void appendError(String data){
        owner.appendError(data);
        sendCount = 0;
    }

    /**
     * 获取调用者的类型
     * @return
     */
    public String getOwnerClassName(){
        return owner.getOwnerClassName();
    }

    public CallOwner getOwner() {
        return owner;
    }

    public void setOwner(CallOwner owner) {
        this.owner = owner;
    }
}
